package com.issac.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.issac.common.R;
import com.issac.entity.Accessory;
import com.issac.mapper.AccessoryMapper;
import com.issac.service.AccessoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName AccessoryServiceImpl
 * @Author zy
 * @Date 2021/11/5 20:06
 * @Description AccessoryServiceImpl
 * @Version 1.0
 */
@Service
public class AccessoryServiceImpl implements AccessoryService {
    @Autowired
    private AccessoryMapper mapper;

    @Override
    public R getAccessoryByFruitId(int id) {
        List<Accessory> list = null;
        try {
            QueryWrapper<Accessory> wrapper = new QueryWrapper<>();
            wrapper.eq("fruit_id",id);
            list = mapper.selectList(wrapper);
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(list);
        }
    }

    @Override
    public R addAccessory(Accessory accessory) {
        int result = 0;
        try {
            // 为实现主键自增，重塑对象
            String accessoryName = accessory.getAccessoryName();
            String fruitId = accessory.getFruitId();
            double price = accessory.getPrice();
            Accessory needAccessory = new Accessory(fruitId,accessoryName, price);

            result = mapper.insert(needAccessory);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(result);
        }
    }

    @Override
    public R updateAccessory(Accessory accessory) {
        int result = 0;
        try {
            result = mapper.updateById(accessory);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(result);
        }
    }

    @Override
    public R deleteAccessory(Accessory[] accessoryList) {
        int result = 0;
        try {
            ArrayList<String> list = new ArrayList<>();
            for (Accessory accessory : accessoryList) {
                list.add(accessory.getAccessoryId());
            }
            mapper.deleteBatchIds(list);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(result);
        }
    }
}